package com.kd.juhaowan.ui;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;


import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallbackProxy;
import com.kd.juhaowan.R;
import com.kd.juhaowan.http.api.CommentListApi;
import com.kd.juhaowan.http.api.GameDetailApi;
import com.kd.juhaowan.http.api.GameDownloadApi;
import com.kd.juhaowan.http.model.CommentModel;
import com.kd.juhaowan.http.model.GameModel;
import com.kd.juhaowan.http.model.HttpData;
import com.kd.juhaowan.http.model.HttpListData;
import com.kd.juhaowan.ui.adapter.CommonFragmentPagerAdapter;
import com.kd.juhaowan.ui.fragment.GameCommentFragment;
import com.kd.juhaowan.ui.fragment.GameDetailFragment;
import com.kd.juhaowan.utils.DeviceUtil;
import com.kd.juhaowan.utils.LogUtil;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class GameDetailActivity2 extends BaseActivity{

    @BindView(R.id.magic_indicator1)
    MagicIndicator magicIndicator;

    @BindView(R.id.main_activity_viewpager)
    ViewPager mMainViewPager;
    String[] mMainTabText = new String[]{"详情","评论"};
    @BindView(R.id.login_confirm)
    TextView downloadView;
    @OnClick(R.id.actvity_back)
    public void onBackClick(){
        finish();
    }
    @Override
    protected int getViewLayoutResourceId() {
        return R.layout.activity_gamedetail2;
    }
    private String  gameid;
    private boolean defaultLoad;
    private GameModel model;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        gameid =getIntent().getStringExtra("id");
        defaultLoad = getIntent().getBooleanExtra("startdownload",false);

    initData();
    }

    @Override
    protected void reInitDate() {
        initData();
    }

    private void initData(){
        EasyHttp.post(this).api(new GameDetailApi(gameid)).request(new HttpCallbackProxy<HttpData<GameModel>>(this){
            @Override
            public void onHttpSuccess(HttpData<GameModel> result, boolean cache) {
                super.onHttpSuccess(result, cache);
                model = result.getData();

                if(DeviceUtil.isInstallApp(getApplicationContext(),model.getGame_package_name())){
                    downloadView.setText("启动");
                }else{
                    downloadView.setText("立即下载（"+model.getGame_package_size()+"）");
                }
                if(TextUtils.isEmpty(model.getUrlfile())){
                    downloadView.setVisibility(View.GONE);
                }
                if(defaultLoad){
                    startDownload(result.getData());
                }
//                initFragmentTab();
                getComment();
            }
        });
    }

    private int commentNumber ;
    private HttpListData<CommentModel> commentModels;
    private void getComment(){
        EasyHttp.post(this).api(new CommentListApi(gameid,1,"time_desc")).request(new HttpCallbackProxy<HttpListData<CommentModel>>(this){
            @Override
            public void onHttpSuccess(HttpListData<CommentModel> result, boolean cache) {
                super.onHttpSuccess(result, cache);
                commentNumber = result.getData().getCount();
                commentModels = result;
                initFragmentTab();
            }
        });
    }
    public void startDownload(){
        startDownload(model);
    }
    private void startDownload(GameModel model){
        StringBuilder builder = new StringBuilder(model.getGame_package_name().trim());
//        builder.append(gameid);
        builder.append(".apk");
        File  file = new File(getExternalCacheDir(), builder.toString());
//        mSinglePath = FileDownloadUtils.getDefaultSaveRootPath()+
////                File.separator+"feifei_save"+
//                File.separator+model.getGame_package_name().trim()+".apk";;
        String mSinglePath = file.getAbsolutePath();
        BaseDownloadTask singleTask = FileDownloader.getImpl().create(model.getUrlfile().startsWith("ttps")?"h"+model.getUrlfile():model.getUrlfile())
//                .setPath(mSinglePath,false)
                .setPath(mSinglePath,false)
                .setCallbackProgressTimes(300)
                .setMinIntervalUpdateSpeed(400)
                //.setTag()
                .setListener(new FileDownloadSampleListener(){
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.d("feifei","pending taskId:"+task.getId()+",soFarBytes:"+soFarBytes+",totalBytes:"+totalBytes+",percent:"+soFarBytes*1.0/totalBytes);

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        downloadView.setText("下载中（"+(int)(soFarBytes*1.0/totalBytes*100)+"%）");
                        Log.d("feifei","progress taskId:"+task.getId()+",soFarBytes:"+soFarBytes+",totalBytes:"+totalBytes+",percent:"+soFarBytes*1.0/totalBytes+",speed:"+task.getSpeed());
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                        startVersionInstallTask(new File(mSinglePath));
                        Log.d("feifei","blockComplete taskId:"+task.getId()+",filePath:"+task.getPath()+",fileName:"+task.getFilename()+",speed:"+task.getSpeed()+",isReuse:"+task.reuse());
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        Log.d("feifei","completed taskId:"+task.getId()+",isReuse:"+task.reuse());
                        startVersionInstallTask(new File(mSinglePath));
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.d("feifei","paused taskId:"+task.getId()+",soFarBytes:"+soFarBytes+",totalBytes:"+totalBytes+",percent:"+soFarBytes*1.0/totalBytes);
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        Log.d("feifei","error taskId:"+task.getId()+",e:"+e.getLocalizedMessage());
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        Log.d("feifei","warn taskId:"+task.getId());
                    }
                });

        singleTaskId =  singleTask.start();

    }

    public void startVersionInstallTask(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        final Uri apkUri;

        if (file == null && !file.exists()) {
            LogUtil.debugLog("gamedetal", "startVersionInstallTask ========> file is not exists");
            return;
        }

        //Android 7.0以上要使用FileProvider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            String authority = getApplication().getPackageName() + ".PhotoPicker";
            apkUri = FileProvider.getUriForFile(getApplicationContext(), authority, file);
//            apkUri = Uri.fromFile(file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            apkUri = Uri.fromFile(file);
        }

        LogUtil.debugLog("gamedetal", "startVersionInstallTask ========> apkUri: " + apkUri.toString());

        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        startActivity(intent);
    }


    private final List<Fragment> fragments = new ArrayList<>();
    public static  boolean  needRefresh =false;

    @Override
    protected void onResume() {
        super.onResume();
        if(needRefresh){
            needRefresh=false;
            EasyHttp.post(this).api(new CommentListApi(gameid,1,"time_desc")).request(new HttpCallbackProxy<HttpListData<CommentModel>>(this){
                @Override
                public void onHttpSuccess(HttpListData<CommentModel> result, boolean cache) {
                    super.onHttpSuccess(result, cache);
                    commentNumber = result.getData().getCount();
//                    commentModels = result;
//                    initFragmentTab();
                    navigatorAdapter.notifyDataSetChanged();
                    if(gameDetailFragment!=null){
                        gameDetailFragment.setCommentModels(result.getData().getList());
                    }
                    if(gameCommentFragment!=null){
                        gameCommentFragment.setCommentModels(result.getData().getList());
                    }
                }
            });
        }
    }

    private GameDetailFragment gameDetailFragment;
    private GameCommentFragment gameCommentFragment;
    CommonNavigatorAdapter navigatorAdapter;
    private void initFragmentTab(){
        if (fragments.isEmpty()) {
            gameDetailFragment = new GameDetailFragment();
            Bundle bundle= new Bundle();
            bundle.putSerializable("model",model);
            bundle.putSerializable("comment",commentModels);
            gameDetailFragment.setArguments(bundle);
            fragments.add(gameDetailFragment);

            gameCommentFragment = new GameCommentFragment();
            Bundle bundle2= new Bundle();
            bundle2.putSerializable("model",model);
            bundle2.putSerializable("comment",commentModels);
            gameCommentFragment.setArguments(bundle2);

            fragments.add(gameCommentFragment);

        }

        mMainViewPager.setOffscreenPageLimit(fragments.size());
        navigatorAdapter = new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return mMainTabText.length;
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(context);

                // load custom layout
                View customLayout = LayoutInflater.from(context).inflate(R.layout.mall_view_tab_gamedetail, null);

                final TextView titleText = (TextView) customLayout.findViewById(R.id.mall_view_tab_title);
                final TextView tipText = (TextView) customLayout.findViewById(R.id.mall_view_tab_tip);
                tipText.setVisibility(index==0?View.GONE:View.VISIBLE);
                tipText.setText(commentNumber+"");

                titleText.setText(mMainTabText[index]);
                commonPagerTitleView.setContentView(customLayout);

                commonPagerTitleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {

                    @Override
                    public void onSelected(int index, int totalCount) {
                        titleText.setTextColor(getColor(R.color.black));
                        titleText.setTextSize(18);

                    }

                    @Override
                    public void onDeselected(int index, int totalCount) {
                        titleText.setTextColor(getColor(R.color.login_33));
                        titleText.setTextSize(14);
                    }

                    @Override
                    public void onLeave(int index, int totalCount, float leavePercent, boolean leftToRight) {
//                        titleImg.setScaleX(1.3f + (0.8f - 1.3f) * leavePercent);
//                        titleImg.setScaleY(1.3f + (0.8f - 1.3f) * leavePercent);
                    }

                    @Override
                    public void onEnter(int index, int totalCount, float enterPercent, boolean leftToRight) {
//                        titleImg.setScaleX(0.8f + (1.3f - 0.8f) * enterPercent);
//                        titleImg.setScaleY(0.8f + (1.3f - 0.8f) * enterPercent);
                    }
                });

                commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mMainViewPager.setCurrentItem(index);
                    }
                });

                return commonPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
//                LinePagerIndicator indicator = new LinePagerIndicator(context);
//                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                return null;
            }
        };
        mMainViewPager.setAdapter(new CommonFragmentPagerAdapter(getSupportFragmentManager(), fragments));
//        magicIndicator.setBackgroundColor(Color.WHITE);
        CommonNavigator commonNavigator = new CommonNavigator(getApplicationContext());
        commonNavigator.setAdjustMode(false);
        commonNavigator.setAdapter(navigatorAdapter);
        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator, mMainViewPager);
    }

    public void goToAllComment(){
        mMainViewPager.setCurrentItem(1);
    }

    private int singleTaskId;
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(singleTaskId!=0){
            FileDownloader.getImpl().pause(singleTaskId);

        }
//        FileDownloader.getImpl().pause(downloadId2);
    }

    @OnClick(R.id.login_confirm)
    public void onLoginClick(View view){
        if(DeviceUtil.isInstallApp(getApplicationContext(),model.getGame_package_name())){
            final Intent intent = getApplication().getPackageManager().getLaunchIntentForPackage(model.getGame_package_name());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            startActivity(intent);

        }else {
            EasyHttp.post(this).api(new GameDownloadApi(gameid)).request(new HttpCallbackProxy<HttpData<GameModel>>(this){
                @Override
                public void onHttpSuccess(HttpData<GameModel> result, boolean cache) {
                    super.onHttpSuccess(result, cache);
                    startDownload();
                }
            });


        }
    }
}
